<template>
	<view class="member-page pageBg">
		<view @click="fanhui('/pages/gengduo/components/tianxieList/tianxieList')" class="fanhui">
			<uni-icons type="left" size="30"></uni-icons>
		</view>
		<view class="tun">
            <view class="title">修改填写记录</view>
		    <!-- 加载状态 -->
		    <view v-if="loading" class="loading">
			    <text>加载中...</text>
		    </view>
		
		    <!-- 表单内容 -->
		    <view v-else class="form-section">
			<view class="section-title">修改模块</view>
			<view class="form-content">
				<view class="form-item">
					<text class="label">报修人：</text>
					<input class="input-field" v-model="formData.reporter" placeholder="请输入报修人姓名" />
				</view>

				<view class="form-item">
					<text class="label">报修院系：</text>
					<picker @change="onDepartmentChange" :value="departmentIndex" :range="departments">
						<view class="picker-view">
							<text>{{ formData.department || '请选择学院/部门' }}</text>
							<uni-icons class="arrow" type="down"></uni-icons>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">周次：</text>
					<input class="input-field" v-model="formData.week" placeholder="请输入周次，只需要数字" />
				</view>

				<view class="form-item">
					<text class="label">处理人：</text>
					<input class="input-field" v-model="formData.handler" placeholder="请输入处理人姓名" />
				</view>

				<view class="form-item">
					<text class="label">报修时间：</text>
					<view class="date-picker" @click="showRepairDatePicker = true">
						<text>{{ formData.repairTime || '请选择报修时间' }}</text>
						<uni-icons class="arrow" type="down"></uni-icons>
					</view>
				</view>

				<view class="form-item">
					<text class="label">故障教室/书院：</text>
					<input class="input-field" v-model="formData.faultLocation" placeholder="例如：勤者楼301或綦河书院3104" />
				</view>

				<view class="form-item">
					<text class="label">是否为外聘教师：</text>
					<radio-group @change="onExternalTeacherChange">
						<label class="radio-item radio-item-first">
							<radio value="是" :checked="formData.isExternalTeacher === '是'" />
							<text>是</text>
						</label>
						<label class="radio-item">
							<radio value="否" :checked="formData.isExternalTeacher === '否'" />
							<text>否</text>
						</label>
					</radio-group>
				</view>

				<view class="form-item">
					<text class="label">报修方式：</text>
					<picker @change="onRepairMethodChange" :value="repairMethodIndex" :range="repairMethods">
						<view class="picker-view">
							<text>{{ formData.repairMethod || '请选择报修方式' }}</text>
							<uni-icons class="arrow" type="down"></uni-icons>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">报修类型：</text>
					<picker @change="onRepairTypeChange" :value="repairTypeIndex" :range="repairTypes">
						<view class="picker-view">
							<text>{{ formData.repairType || '请选择报修类型' }}</text>
							<uni-icons class="arrow" type="down"></uni-icons>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">是否更换设备：</text>
					<radio-group @change="onEquipmentChangeChange">
						<label class="radio-item radio-item-first">
							<radio value="是" :checked="formData.isEquipmentChanged === '是'" />
							<text>是</text>
						</label>
						<label class="radio-item">
							<radio value="否" :checked="formData.isEquipmentChanged === '否'" />
							<text>否</text>
						</label>
					</radio-group>
				</view>

				<view class="form-item">
					<text class="label">处理情况：</text>
					<radio-group @change="onHandlingStatusChange">
						<label class="radio-item radio-item-first">
							<radio value="已处理" :checked="formData.handlingStatus === '已处理'" />
							<text>已处理</text>
						</label>
						<label class="radio-item">
							<radio value="未处理" :checked="formData.handlingStatus === '未处理'" />
							<text>未处理</text>
						</label>
					</radio-group>
				</view>

				<view class="form-item">
					<text class="label">故障发生原因：</text>
					<picker @change="onFormFaultReasonChange" :value="formFaultReasonIndex" :range="faultReasons">
						<view class="picker-view">
							<text>{{ formData.faultReasonType || '请选择故障发生原因' }}</text>
							<uni-icons class="arrow" type="down"></uni-icons>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="label">处理方式、或未处理原因：</text>
					<textarea class="textarea-field" v-model="formData.faultReason"
						placeholder="请输入故障处理方式、或未处理原因(请按照如何处理+解决成功没)" :maxlength="200"></textarea>
				</view>
			</view>

			<button class="submit-btn" @click="handleSubmit">提交修改</button>

			<!-- 报修时间选择器弹窗 -->
			<view v-if="showRepairDatePicker" class="popup-overlay" @click="showRepairDatePicker = false">
				<view class="date-picker-popup" @click.stop>
					<view class="popup-header">
						<text class="cancel-btn" @click="showRepairDatePicker = false">取消</text>
						<text class="title">选择报修时间</text>
						<text class="confirm-btn" @click="confirmRepairDate">确定</text>
					</view>
					<picker-view class="picker-view" :value="repairDatePickerValue" @change="onRepairDatePickerChange">
						<picker-view-column>
							<view v-for="(item, index) in years" :key="index" class="picker-item">{{ item }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view v-for="(item, index) in months" :key="index" class="picker-item">{{ item }}月</view>
						</picker-view-column>
						<picker-view-column>
							<view v-for="(item, index) in days" :key="index" class="picker-item">{{ item }}日</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</view>
        </view>
		
	</view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { tianxieListAPI } from '@/api/tianxieList'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const recordId = ref('')

// 表单数据
const formData = reactive({
	// 报修人
	reporter: '',
	// 报修院系
	department: '',
	// 周次
	week: '',
	// 处理人
	handler: userStore.username,
	// 报修时间
	repairTime: '',
	// 故障教室/书院
	faultLocation: '',
	// 报修类型
	repairType: '',
	// 是否为外聘教师
	isExternalTeacher: '',
	// 报修方式
	repairMethod: '',
	// 是否更换设备
	isEquipmentChanged: '',
	// 处理情况
	handlingStatus: '',
	// 故障发生原因
	faultReasonType: '',
	// 故障详细描述
	faultReason: ''
})

// 选择器数据
const departments = [
	'大健康管理学院',
	'大数据学院',
	'地域文化与城市发展研究院',
	'电影评论中心',
	'电影商务产业学院',
	'创意写作学院',
	'淬炼商学院',
	'基建后勤处',
	'计算机学院',
	'剧本杀学院',
	'就业创业指导与服务中心/创业学院',
	'竞技体育中心',
	'酒店商务产业学院',
	'马克思主义学院',
	'美术与设计学院',
	'人力资源处',
	'软件工程学院',
	'实训中心',
	'书院部',
	'数理教学部',
	'数字经济与信息管理学院',
	'数字媒体产业学院',
	'双体软件精英产业学院',
	'通识教学部',
	'通信与信息工程学院',
	'图书馆',
	'外聘教师',
	'网络与信息管理中心',
	'信息安全学院',
	'新商科教学部',
	'戏剧影视学院',
	'艺术教育中心',
	'院领导',
	'远景学院',
	'学生处',
	'瀛洲科幻学院',
	'重点实验室',
	'物理教研室'
]

const repairTypes = [
	'教师',
	'话筒',
	'投影仪',
	'音响',
	'云桌面',
	'线路',
	'显示器',
	'多媒体柜',
	'电路，外设',
	'中控',
	'云终端',
	'幕布',
	'其他'
]

const repairMethods = ['电话报修', '多媒体群报修', '其他']

// 故障发生原因选项
const faultReasons = [
	'教师不会用',
	'教师将线路插错',
	'教师自行调整设备',
	'教师未规范使用',
	'教师导致设备故障',
	'教师要求新装软件',
	'话筒损坏',
	'话筒串音',
	'话筒噪音',
	'话筒无法匹配接收器',
	'话筒充电线损坏',
	'音响音量问题',
	'音响功放板故障',
	'音响噪音',
	'多媒体柜锁问题',
	'云桌面问题，重启可解决',
	'云桌面软件问题，需调整或重装软件',
	'线路掉落',
	'线路松动',
	'云终端故障',
	'空开跳闸',
	'电源线故障',
	'插线板故障',
	'显示器问题，微调可解决',
	'显示器故障，需更换显示器',
	'投影仪死机，重启可解决',
	'投影仪位置不正',
	'投影仪硬件故障，需维修投影仪',
	'投影仪问题，微调可解决',
	'中控线路问题',
	'中控死机，重启可解决',
	'中控硬件故障，需更换中控',
	'幕布',
	'键盘',
	'鼠标',
	'插头没有插好',
	'VGA线故障或接触不良',
	'网络问题',
	'其他'
]

const departmentIndex = ref(0)
const repairTypeIndex = ref(0)
const repairMethodIndex = ref(0)
const formFaultReasonIndex = ref(0)
const showRepairDatePicker = ref(false)

// 日期选择器数据
const currentDate = new Date()
const years = Array.from({
	length: 10
}, (_, i) => currentDate.getFullYear() - 5 + i)
const months = Array.from({
	length: 12
}, (_, i) => i + 1)
const days = computed(() => {
	const year = years[repairDatePickerValue.value[0]]
	const month = months[repairDatePickerValue.value[1]]
	const daysInMonth = new Date(year, month, 0).getDate()
	return Array.from({
		length: daysInMonth
	}, (_, i) => i + 1)
})

const repairDatePickerValue = ref([5, currentDate.getMonth(), currentDate.getDate() - 1])

// 返回上一页
	const fanhui = (e) => {
	uni.navigateBack()
}

// 获取记录详情
const getRecordDetail = async (id) => {
	try {
		loading.value = true
		const response = await tianxieListAPI.getTianxieDetail(id)
		
		console.log('完整响应数据:', response) // 调试日志
		
		// 根据request.js的实现，数据直接在response中
		const data = response
		
		console.log('提取的数据:', data) // 调试日志
		
		if (data) {
			// 回显数据到表单
			formData.reporter = data.reporter || ''
			formData.department = data.department || ''
			formData.week = data.week ? data.week.replace('第', '').replace('周', '') : ''
			formData.handler = data.handler || ''
			formData.repairTime = data.repairTime || ''
			formData.faultLocation = data.faultLocation || ''
			formData.repairType = data.repairType || ''
			// 修复布尔值转换
			formData.isExternalTeacher = data.isExternalTeacher === true ? '是' : '否'
			formData.repairMethod = data.repairMethod || ''
			formData.isEquipmentChanged = data.isEquipmentChanged === true ? '是' : '否'
			formData.handlingStatus = data.handlingStatus || ''
			formData.faultReasonType = data.faultReasonType || ''
			formData.faultReason = data.faultReason || ''
			
			console.log('回显后的表单数据:', formData) // 调试日志
			
			// 设置选择器索引
			setPickerIndexes()
		} else {
			console.error('未找到有效数据')
			uni.showToast({
				title: '数据格式错误',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取记录详情失败:', error)
		uni.showToast({
			title: '获取数据失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 设置选择器索引
const setPickerIndexes = () => {
	console.log('开始设置选择器索引，当前表单数据:', formData) // 调试日志
	
	// 设置院系索引
	const deptIndex = departments.findIndex(dept => dept === formData.department)
	departmentIndex.value = deptIndex >= 0 ? deptIndex : 0
	console.log('院系索引设置:', deptIndex, '->', departmentIndex.value)
	
	// 设置报修类型索引
	const typeIndex = repairTypes.findIndex(type => type === formData.repairType)
	repairTypeIndex.value = typeIndex >= 0 ? typeIndex : 0
	console.log('报修类型索引设置:', typeIndex, '->', repairTypeIndex.value)
	
	// 设置报修方式索引
	const methodIndex = repairMethods.findIndex(method => method === formData.repairMethod)
	repairMethodIndex.value = methodIndex >= 0 ? methodIndex : 0
	console.log('报修方式索引设置:', methodIndex, '->', repairMethodIndex.value)
	
	// 设置故障原因索引
	const reasonIndex = faultReasons.findIndex(reason => reason === formData.faultReasonType)
	formFaultReasonIndex.value = reasonIndex >= 0 ? reasonIndex : 0
	console.log('故障原因索引设置:', reasonIndex, '->', formFaultReasonIndex.value)
}

// 日期选择器事件
const onRepairDatePickerChange = (e) => {
	repairDatePickerValue.value = e.detail.value
}

const confirmRepairDate = () => {
	const year = years[repairDatePickerValue.value[0]]
	const month = months[repairDatePickerValue.value[1]]
	const day = days.value[repairDatePickerValue.value[2]]
	formData.repairTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
	showRepairDatePicker.value = false
}

// 选择器事件
const onDepartmentChange = (e) => {
	departmentIndex.value = e.detail.value
	formData.department = departments[e.detail.value]
}

const onRepairTypeChange = (e) => {
	repairTypeIndex.value = e.detail.value
	formData.repairType = repairTypes[e.detail.value]
}

const onRepairMethodChange = (e) => {
	repairMethodIndex.value = e.detail.value
	formData.repairMethod = repairMethods[e.detail.value]
}

const onExternalTeacherChange = (e) => {
	formData.isExternalTeacher = e.detail.value
}

const onEquipmentChangeChange = (e) => {
	formData.isEquipmentChanged = e.detail.value
}

const onHandlingStatusChange = (e) => {
	formData.handlingStatus = e.detail.value
}

// 表单中故障发生原因选择器事件
const onFormFaultReasonChange = (e) => {
	formFaultReasonIndex.value = e.detail.value
	formData.faultReasonType = faultReasons[e.detail.value]
}

// 提交修改
const handleSubmit = async () => {
	// 验证必填字段
	const requiredFields = ['reporter', 'department', 'week', 'handler', 'repairTime', 'faultLocation',
		'repairType', 'faultReasonType'
	]
	const missingFields = requiredFields.filter(field => !formData[field])

	if (missingFields.length > 0) {
		uni.showToast({
			title: '请填写所有必填字段',
			icon: 'none'
		})
		return
	}

	try {
		// 显示加载提示
		uni.showLoading({
			title: '提交中...'
		})

		// 转换数据格式以匹配API要求
		const apiData = {
			reporter: formData.reporter,
			department: formData.department,
			week: formData.week.startsWith('第') ? formData.week : `第${formData.week}周`,
			handler: formData.handler,
			repairTime: formData.repairTime,
			faultLocation: formData.faultLocation,
			repairType: formData.repairType,
			isExternalTeacher: formData.isExternalTeacher === '是',
			repairMethod: formData.repairMethod || '在线报修',
			isEquipmentChanged: formData.isEquipmentChanged === '是',
			handlingStatus: formData.handlingStatus === '已处理' ? '已处理' : '待处理',
			faultReasonType: formData.faultReasonType,
			faultReason: formData.faultReason
		}

		// 调用修改API
		await tianxieListAPI.patchTianxiePatch(recordId.value, apiData)
		
		// 隐藏加载提示
		uni.hideLoading()

		// 显示成功提示
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})

		// 延迟返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1000)

	} catch (error) {
		// 隐藏加载提示
		uni.hideLoading()
		
		console.error('修改失败:', error)
		uni.showToast({
			title: error.message || '修改失败，请重试',
			icon: 'none'
		})
	}
}

// 页面加载时获取数据
onMounted(() => {
	// 获取页面参数中的id
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options
	
	if (options.id) {
		recordId.value = options.id
		getRecordDetail(options.id)
	} else {
		uni.showToast({
			title: '缺少记录ID',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
})
</script>

<style lang="scss" scoped>
.member-page {
		padding: 20rpx;
	}
.fanhui {
	margin-top: 80rpx;
}
.tun{
    position: relative;
    bottom: 80rpx;
}
.title {
	font-size: 36rpx;
	font-weight: bold;
	text-align: center;
	margin: 40rpx 0;
	color: #333;
}

.loading {
	text-align: center;
	padding: 40rpx;
	color: #999;
}

.form-section {
	position: relative;
}

.imgBox {
	position: absolute;
	top: -20rpx;
	right: 20rpx;
	height: 100rpx;
	width: 500rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
	border-left: 6rpx solid #007aff;
}

.form-section {
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.form-content {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.form-item {
	display: flex;
	align-items: center;
	flex-direction: row;
	margin-bottom: 20rpx;

	.label {
		width: 160rpx;
		font-size: 28rpx;
		color: #333;
		flex-shrink: 0;
	}

	.input-field {
		flex: 1;
		height: 70rpx;
		padding: 0 20rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;

		&:focus {
			border-color: #007aff;
			background: white;
		}
	}

	.textarea-field {
		flex: 1;
		height: 110rpx;
		padding: 10rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		background: #fafafa;

		&:focus {
			border-color: #007aff;
			background: white;
		}
	}

	.date-picker,
	.picker-view {
		flex: 1;
		height: 70rpx;
		padding: 0 20rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.arrow {
			margin-left: 20rpx;
			color: #999;
			font-size: 15rpx;
		}
	}

	.radio-item {
		display: inline-flex;
		align-items: center;

		text {
			margin-left: 10rpx;
			font-size: 28rpx;
		}
	}

	.radio-item-first {
		margin-right: 30rpx;
	}
}

.submit-btn {
	width: 100%;
	height: 80rpx;
	background: linear-gradient(135deg, #34c759, #28a745);
	color: white;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: bold;
	margin-top: 40rpx;

	&:active {
		opacity: 0.8;
	}
}

.popup-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.date-picker-popup {
	background: white;
	border-radius: 20rpx 20rpx 0 0;
	padding: 20rpx;
	width: 100%;
	max-height: 60vh;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f0f0f0;

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.cancel-btn,
	.confirm-btn {
		font-size: 28rpx;
		color: #007aff;
		padding: 10rpx 20rpx;
	}
}

.picker-view {
	height: 400rpx;
	margin-top: 20rpx;
}

.picker-item {
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #333;
}
</style>